package com.shjn.squirrel.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.shjn.squirrel.R;
import com.shjn.squirrel.application.MyApplication;
import com.shjn.squirrel.bean.storageBean.BottleState;
import com.shjn.squirrel.customView.BackAndTimerView;
import com.shjn.squirrel.model.Constant;
import com.shjn.squirrel.model.LocalStorage;
import com.shjn.squirrel.model.UserInfoCache;
import com.shjn.squirrel.utils.MeasureScreenUtils;
import com.shjn.squirrel.utils.SoundPlayUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * 投口打开
 */
public class UserOpenDeliverFragment extends BaseFragment implements View.OnClickListener {

    private static UserOpenDeliverFragment instance;
    private TextView mTvOpenTip;
    private Button mBtnOpen;
    private RelativeLayout imgs_rel;
    private RelativeLayout normal_rel;
    private RelativeLayout bottle_rel;
    private TextView mTvCount;
    private boolean isDelivered = false;
    private TextView mTv60g;

    public UserOpenDeliverFragment() {
    }

    public synchronized static UserOpenDeliverFragment getInstance() {
        if (instance == null) {
            instance = new UserOpenDeliverFragment();
        }
        return instance;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return createView(inflater, R.layout.user_open_deliver, container);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initTimer();
        initView();
    }

    /**
     * 初始化倒计时器
     */
    private void initTimer() {
        //加载定时器面板，设置定时时间
//        mActivity.mBackAndTimer.setOnBackListener(null).setBackVisibleState(false)
//                .setOnTimerFinishListener(new BackAndTimerView.OnTimerFinishListener() {
//                    @Override
//                    public void onTimerFinish() {
//                        gotoFinishPage();
//
//                    }
//                }).setTime(LocalStorage.getWorkSetting(MyApplication.getInstance()).getHoldTime()).setVisibleState(true).start();
        mActivity.mBackAndTimer.setOnBackListener(null).setBackVisibleState(false)
                .setOnTimerFinishListener(new BackAndTimerView.OnTimerFinishListener() {
                    @Override
                    public void onTimerFinish() {
                        gotoFinishPage();

                    }
                }).setTime(60).setVisibleState(true).start();
    }

    /**
     * 初始化相关控件
     */
    private void initView() {
        isDelivered = false;
        imgs_rel = (RelativeLayout) mView.findViewById(R.id.imgs_show);
        normal_rel = (RelativeLayout) mView.findViewById(R.id.normal);
        bottle_rel = (RelativeLayout) mView.findViewById(R.id.deliver_bottle);
        mTvOpenTip = (TextView) mView.findViewById(R.id.tv_opening_tip);
        mTvCount = (TextView) mView.findViewById(R.id.tv_count);
        mBtnOpen = (Button) mView.findViewById(R.id.btn_open);
        mBtnOpen.setOnClickListener(this);
        mTv60g = (TextView) mView.findViewById(R.id.tv_60g);
        if (UserInfoCache.category.equals(Constant.glass) ||
                UserInfoCache.category.equals(Constant.harm)) {
            mTv60g.setVisibility(View.INVISIBLE);
        }
        LayoutInflater.from(mActivity).inflate(Constant.categoryMap.get(UserInfoCache.category)[0], imgs_rel, true);
        EventBus.getDefault().register(this);
        //打开投口
//        Log.i("info", "androidC51: "+Constant.numberMap.get(Constant.categoryMap.get(UserInfoCache.category)[3]));
//        mActivity.serialPortUtils.sendSerialPort("androidC51:" + Constant.numberMap.get(Constant.categoryMap.get(UserInfoCache.category)[3]) + ";");
        //模拟串口通知
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mActivity.postPitchOpen(1);
            }
        }).start();
    }

    /**
     * 事件上报通知
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String event) {
        //投口打开
        if (event.equals("pitchOpen")) {
            mTvOpenTip.setText("箱门已打开，请投递");
            mBtnOpen.setEnabled(true);
            mBtnOpen.setText("投递完成");
            mBtnOpen.setTextColor(Color.parseColor("#FFFFFF"));
        } else if (event.matches("[0-9]+")) {
            //垃圾投递量
            if (Integer.parseInt(event) != 0) {
                //标记本次有投递
                isDelivered = true;
                if (UserInfoCache.category.equals(Constant.bottle)) {
                    //本次投递的数量
                    int count = Integer.parseInt(event);
                    //设置饮料瓶动态计数布局
                    normal_rel.setVisibility(View.INVISIBLE);
                    bottle_rel.setVisibility(View.VISIBLE);
                    mBtnOpen.setY(258 * MeasureScreenUtils.getDensity(mActivity));
                    //记录当前投递的垃圾量
                    UserInfoCache.nowDeliverQuantity = count;
                    //显示当前饮料瓶投递的个数
                    SpannableString spannableString = new SpannableString("已投递 " + count + " 个");
                    spannableString.setSpan(new RelativeSizeSpan((float) (27 / 13.0)), 4, spannableString.length() - 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                    spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#429DFB")), 4, spannableString.length() - 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                    mTvCount.setText(spannableString);
                } else {
                    //本次投递的重量
                    double weight = Double.parseDouble(event) * 10 / 1000;
                    //记录非饮料瓶当前投递的垃圾量
                    UserInfoCache.nowDeliverQuantity = weight;
                }

            }

        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //投递完成
            case R.id.btn_open:
                gotoFinishPage();
                break;
            default:
                break;
        }
    }

    //跳转到本次投递记录页
    private void gotoFinishPage() {
        mActivity.mBackAndTimer.stop();
        mBtnOpen.setEnabled(false);
        mBtnOpen.setTextColor(Color.parseColor("#999999"));
        new Thread(new Runnable() {
            @Override
            public void run() {
                //----------测试用-------------//
                //延迟4秒，确保称重完成    ( 测试1秒)
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //投递确认，关闭投口
//                mActivity.serialPortUtils.sendSerialPort("androidC50:0;");
                //判断本次投递情况
                if (!isDelivered) {
                    //本次未投递
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            //----------测试用-------------//
                            //关闭投口过程3秒 ( 测试1秒)
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            //清空本次投递的垃圾量
                            UserInfoCache.nowDeliverQuantity = 0;
                            //选择继续投递或结束投递语音提示
                            SoundPlayUtils.play(14);
                            mActivity.getFragmentManager().beginTransaction()
                                    .replace(R.id.mid, UserRecordNoneFragment.getInstance())
                                    .commit();
                        }
                    }).start();
                } else {
                    //本次有投递
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            //----------测试用-------------//
                            //关闭投口过程3秒 ( 测试1秒)
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            //添加本次投递记录
                            UserInfoCache.addRecord(UserInfoCache.nowDeliverQuantity);
                            if (UserInfoCache.category.equals(Constant.bottle)) {
                                //更新饮料瓶分类桶状态
                                BottleState bottleState = LocalStorage.getBottleState(MyApplication.getInstance());
                                bottleState.setCount(bottleState.getCount() + (int) UserInfoCache.nowDeliverQuantity);
                                bottleState.setCanFullStatus(bottleState.getCount() >= Constant.bottleLimit ? 2 :
                                        (bottleState.getCount() >= Constant.bottleLimit * 0.8 ? 1 : 0));
                            }
                            //清空本次投递的垃圾量
                            UserInfoCache.nowDeliverQuantity = 0;
                            //选择继续投递或结束投递语音提示
                            SoundPlayUtils.play(14);
                            if (UserInfoCache.records.size() == 1) {
                                mActivity.getFragmentManager().beginTransaction()
                                        .replace(R.id.mid, UserRecordOnceFragment.getInstance())
                                        .commit();
                            } else if (UserInfoCache.records.size() > 1 && UserInfoCache.records.size() <= 3) {
                                mActivity.getFragmentManager().beginTransaction()
                                        .replace(R.id.mid, UserRecordLessFragment.getInstance())
                                        .commit();
                            } else {
                                mActivity.getFragmentManager().beginTransaction()
                                        .replace(R.id.mid, UserRecordMoreFragment.getInstance())
                                        .commit();
                            }
                        }
                    }).start();
                }
            }
        }).start();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
